package com.eat.service.impl;

import com.eat.dto.GoodsSalesDTO;
import com.eat.entity.Orders;
import com.eat.mapper.OrderMapper;
import com.eat.mapper.UserMapper;
import com.eat.service.ReportService;
import com.eat.service.WorkspaceService;
import com.eat.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImp implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> list =new ArrayList<>();

        list.add(begin);
        while (!begin.equals(end)){
            begin= begin.plusDays(1);
            list.add(begin);
        }
        List<Double> listDouble = new ArrayList<>();
        for (LocalDate localDate : list) {

            LocalDateTime dateTime = LocalDateTime.of(localDate, LocalTime.MIN);

            LocalDateTime dateTime1 = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin",dateTime);
            map.put("end",dateTime1);
            map.put("status", Orders.COMPLETED);

            Double allAmount = orderMapper.sumByMap(map);
            allAmount = allAmount == null ? 0.0 : allAmount;
            listDouble.add(allAmount);
            //select sum(amount) from orders where order_time between ? and ? and status = ?
        }


        String join = StringUtils.join(list, ",");
        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(StringUtils.join(listDouble,","))
                .build();

        return build ;
    }

    /**
     * 统计指定时间的区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> list =new ArrayList<>();

        list.add(begin);
        while (!begin.equals(end)){
            begin= begin.plusDays(1);
            list.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();

        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : list) {
            LocalDateTime of = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime of1 = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            //统计每天的总用户量
            map.put("end",of1);
            Integer totalUser = userMapper.countByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);
            //统计每天的新用户量
            map.put("begin",of);
            Integer newUser = userMapper.countByMap(map);
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
        }

        UserReportVO build = UserReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();

        return build;
    }

    /**
     * 查询时间段内订单总数
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> list =new ArrayList<>();

        list.add(begin);
        while (!begin.equals(end)){
            begin= begin.plusDays(1);
            list.add(begin);
        }
        //1表示订单总数，2表示有效订单数
        Integer o1=0;
        Integer o2=0;
        List<Integer> or1 = new ArrayList<>();
        List<Integer> or2 = new ArrayList<>();
        for (LocalDate localDate : list) {

            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            //统计总订单数
            map.put("begin",min);
            map.put("end",max);
            Integer orders1 = orderMapper.getOrdersStatistics(map);
            o1+=orders1;
            or1.add(orders1);
            //统计有效订单数
            map.put("status",Orders.COMPLETED);
            Integer orders2 = orderMapper.getOrdersStatistics(map);
            o2+=orders2;
            or2.add(orders2);
        }
        Double orderCompleteRate=0.0;
        if (o2!=0){
             orderCompleteRate = Double.valueOf(o2)/o1;
        }

        OrderReportVO build = OrderReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .validOrderCount(o2)
                .totalOrderCount(o1)
                .orderCompletionRate(orderCompleteRate)
                .orderCountList(StringUtils.join(or1,","))
                .validOrderCountList(StringUtils.join(or2,","))
                .build();

        return build;
    }

    /**
     * 统计指定时间区间前十
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTO = orderMapper.getSalesTop(beginTime,endTime);

        List<String> names = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    /**
     * 导出excel
     * @param response
     */
    @Override
    public void getReportExport(HttpServletResponse response) throws IOException {

        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        XSSFWorkbook xssfWorkbook =new XSSFWorkbook(in);
        XSSFSheet sheet1 = xssfWorkbook.getSheetAt(0);

        sheet1.getRow(1).getCell(1).setCellValue("时间"+begin+"至"+end);
        XSSFRow row = sheet1.getRow(3);
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(6).setCellValue(businessData.getNewUsers());
        row = sheet1.getRow(4);
                row.getCell(2).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getUnitPrice());

        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);

            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessData1.getTurnover());
            row.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData1.getUnitPrice());
            row.getCell(6).setCellValue(businessData1.getNewUsers());

        }
        //通过输出流将Excel文件下载到客户端浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        xssfWorkbook.write(outputStream);
        outputStream.close();
        xssfWorkbook.close();
    }
}
